package repository
import (
	"github.com/jinzhu/gorm"
	"car/domain/model"
)
type ICarRepository interface{
    InitTable() error
    FindCarByID(int64) (*model.Car, error)
	CreateCar(*model.Car) (int64, error)
	DeleteCarByID(int64) error
	UpdateCar(*model.Car) error
	FindAll()([]model.Car,error)

}
//创建carRepository
func NewCarRepository(db *gorm.DB) ICarRepository  {
	return &CarRepository{mysqlDb:db}
}

type CarRepository struct {
	mysqlDb *gorm.DB
}

//初始化表
func (u *CarRepository)InitTable() error  {
	return u.mysqlDb.CreateTable(&model.Car{}).Error
}

//根据ID查找Car信息
func (u *CarRepository)FindCarByID(carID int64) (car *model.Car,err error) {
	car = &model.Car{}
	return car, u.mysqlDb.First(car,carID).Error
}

//创建Car信息
func (u *CarRepository) CreateCar(car *model.Car) (int64, error) {
	return car.ID, u.mysqlDb.Create(car).Error
}

//根据ID删除Car信息
func (u *CarRepository) DeleteCarByID(carID int64) error {
	return u.mysqlDb.Where("id = ?",carID).Delete(&model.Car{}).Error
}

//更新Car信息
func (u *CarRepository) UpdateCar(car *model.Car) error {
	return u.mysqlDb.Model(car).Update(car).Error
}

//获取结果集
func (u *CarRepository) FindAll()(carAll []model.Car,err error) {
	return carAll, u.mysqlDb.Find(&carAll).Error
}

